
var app = getApp()
var event = require('../../utils/event')
var config = require('../../config.js')


Page({
    data: {
      topImgs:[],
      scrollTop:0,
      indicatorDots: false,
      autoplay: true,
      interval: 5000,
      duration: 1000,
      tabTxt: ['区域', '面积'],//分类
      hidetop:true,
      tab: [true, true, true],
      pinpaiList: app.globalData.areaList,
      pinpai_id: -1,//区域
      pinpai_txt: '',
      jiageList: app.globalData.sizeList,
      jiage_id: -1,//面积
      jiage_txt: '',
      xiaoliang_id: 0,//销量
      xiaoliang_txt: '',
      themes:[
        {
          navi:'/pages/home/buslis/buslis',
          img:'/img/icon1.png',
          title:'生意转让'
        },
        {
          navi: '/pages/home/sholis/sholis',
          img: '/img/icon2.png',
          title: '商铺出租'
        },
        {
          navi: '/pages/home/builis/builis',
          img: '/img/icon3.png',
          title: '写字楼'
        },
        {
          navi: '/pages/home/lanlis/lanlis',
          img: '/img/icon4.png',
          title: '土地厂房'
        },

      ],
      objHostName:`${config.service.objHostName}`,
      list:[],
      pageSize:8,
      ye:1,
      hideBottomLabel:true,
      overHeight:false,
        head: {
            currentCity: '',
            placestr: '你想住哪儿?'
        },

        indexData: {},
        counts: 10,
        start: 0
    },

    onLoad: function (options) {
      console.log(options)
      if (options.id&&options.bigtyp) {
        wx.navigateTo({
          url: './detail/detail?id=' + options.id + '&bigtyp=' + options.bigtyp,
        })
      }
      this.getDataList();

      const updateManager = wx.getUpdateManager()

      updateManager.onCheckForUpdate(function (res) {
        // 请求完新版本信息的回调
        console.log('hasUpdate:' + res.hasUpdate)
      })

      updateManager.onUpdateReady(function () {
        wx.showModal({
          title: '更新提示',
          content: '新版本已经准备好，是否重启应用？',
          success: function (res) {
            if (res.confirm) {
              // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
              updateManager.applyUpdate()
            }
          }
        })
      })

      updateManager.onUpdateFailed(function () {
        // 新版本下载失败
      })
    },
    onShow: function (options) {
      
      console.log('index-onShow')
      var that = this
      if (that.data.pinpaiList.length == 0) {
        that.getAreaList()
      }
      if(that.data.topImgs.length==0)
      {
        that.getTopImgs()
      }
      return;
        wx.getSetting({
          success(res) {
            console.log(JSON.stringify(res))
            // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
            // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
            // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
            if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
              wx.showModal({
                title: '请求授权当前位置',
                content: '需要获取您的地理位置，请确认授权',
                success: function (res) {
                  if (res.cancel) {
                    wx.showToast({
                      title: '拒绝授权',
                      icon: 'none',
                      duration: 1000
                    })
                  } else if (res.confirm) {
                    wx.openSetting({
                      success: function (dataAu) {
                        if (dataAu.authSetting["scope.userLocation"] == true) {
                          wx.showToast({
                            title: '授权成功',
                            icon: 'success',
                            duration: 1000
                          })
                          //再次授权，调用wx.getLocation的API

                        } else {
                          wx.showToast({
                            title: '授权失败',
                            icon: 'none',
                            duration: 1000
                          })
                        }
                      }
                    })
                  }
                }
              })
            } else if (res.authSetting['scope.userLocation'] == undefined) {
              //调用wx.getLocation的API
              console.log('调用wx.getLocation的API');
              wx.getLocation({
                success: function(res) {
                  console.log('res->'+res)

                },
                fail:function(err)
                {
                  console.log('err->' + err)
                }
              })
            }
            else {
              //调用wx.getLocation的API
              console.log('调用wx.getLocation的API1');
            }
            
          }
        })


        // app.getpol(
        //     function (currentCity) {
        //         that.setData({
        //             'head.currentCity': currentCity
        //         })
        //     }
        // )
    },
   
    onReachBottom: function () {
        var that = this
        // 
        var ye = that.data.ye;
        ye+=1;
        that.setData({
          ye:ye
        });
        wx.showLoading({
          title: '',
        })
        that.getDataList();
    },

    getLoc:function(){
      wx.getLocation({
        success: function(res) {

        },
        fail:function(err){

        },
        complete:function(comp){
          
        }
      })
    },
  // 选项卡
  filterTab: function (e) {
    var overHeight = this.data.overHeight;
    var data = [true, true, true], index = e.currentTarget.dataset.index;
    var newFlag = !this.data.tab[index];

    if(overHeight==false)
    {
      if (newFlag) {
        wx.showTabBar();
        this.setData({
          hidetop: true
        });
      }
      else {
        wx.hideTabBar();
        this.setData({
          hidetop: false
        });
      }
    }
    else
    {
      if (newFlag) {
        wx.showTabBar();
      }
      else {
        wx.hideTabBar();
      }
    }


    data[index] = newFlag;
    this.setData({
      tab: data
    })

    console.log(this.data.tab)
  },

  onShareAppMessage:function(){
      return {
        title: '创美广告',
        desc: '描述',
        path: '/pages/home/index'
        }
  },

  //筛选项点击操作
  filter: function (e) {
    var overHeight = this.data.overHeight;
    if(overHeight)
    {
      this.setData({
        hidetop:false
      });
    }
    else
    {
      this.setData({
        hidetop: true
      });
    }

    wx.showTabBar();

    var self = this
    var id = e.currentTarget.dataset.id
    var txt = e.currentTarget.dataset.txt
    var tabTxt = this.data.tabTxt
    
    switch (e.currentTarget.dataset.index) {
      case '0':
        tabTxt[0] = txt;
        self.setData({
          pinpai_id: id,
          pinpai_txt: txt
        });
        break;
      case '1':
        tabTxt[1] = txt;
        self.setData({
          jiage_id: id,
          jiage_txt: txt
        });
        break;
    }

    self.setData({
      ye:1,
      tab:[true, true, true],
      tabTxt:tabTxt
    })
    //数据筛选
    self.getDataList();
  },

  cancelFilter:function()
  {
    console.log('dddd');
    var overHeight = this.data.overHeight;

    this.setData({
      ye: 1,
      tab: [true, true, true],
      hidetop: !overHeight
    })

    wx.showTabBar();
  },

  getTopImgs:function(){
    wx.showLoading({
      title: '获取顶部图片',
    })
    var that = this;
    wx.request({
      url: `${config.service.topImgUrl}`+'?type=0',
      method:'GET',
      timeout:2000,
      data:{},
      success:function(e)
      {
        wx.hideLoading()
        if (null == e.data.code) {
          wx.showToast({
            title: '获取顶部图片失败',
          })
          return
        }

        let code = e.data.code
        if (1 == code) {
          wx.showToast({
            title: '' + e.data.msg,
          })
          return
        }
        let res = e.data.res
        // console.log("顶部res:"+res)

        var imgs = res.imgs.split(',')
        
        that.setData({
          topImgs: imgs
        })
      },
      fail:f=>{
        wx.hideLoading()
        console.log('f:' + f)
        wx.showToast({
          title: '失败:获取地区',
        })
      }

    })
  },

  getAreaList:function(){
    wx.showLoading({
      title: '获取地区中...',
    })
    //调用数据接口，获取数据
    var that = this;
    wx.request({
      url: `${config.service.areaUrl}`+'?p_id=0',
      method: 'GET',
      timeout: 2000,
      data:{},
      success: function (e) {
        wx.hideLoading()
        console.log('e:'+ JSON.stringify( e.data))
        if(null==e.data.code)
        {
          wx.showToast({
            title: '获取地区失败',
          })
          return
        }
        
        let code = e.data.code
        if(1==code)
        {
          wx.showToast({
            title: ''+e.data.msg,
          })
          return
        }

        let res = e.data.res
        if(res.length)
        {
          app.globalData.areaList = res;
          // console.log('alist:'+config.constant.areaList)
        }
        that.setData({
          pinpaiList: app.globalData.areaList
        })
      },
      fail:f=>{
        wx.hideLoading()
        console.log('f:'+f)
        wx.showToast({
          title: '失败:获取地区',
        })
      }
    })

  },

  showLoading:function(){
    var that = this;
    wx.showNavigationBarLoading()
  },

  hideLoading:function(){
    var that = this;
    wx.hideNavigationBarLoading()
    wx.stopPullDownRefresh()
    wx.hideLoading()
  },

  //加载数据
  getDataList:function () {
    //调用数据接口，获取数据
    var that = this;
    var ye = that.data.ye;
    that.showLoading()
    wx.request({
      url: `${config.service.homeUrl}`,
      method: 'POST',
      timeout: 2000,
      data: {
        row: that.data.pageSize,
        ye: ye,
        area:that.data.pinpai_id,
        size:that.data.jiage_id
      },
      success: function (e) {
        that.hideLoading()
        // wx.hideLoading()
        // console.log('res:' + JSON.stringify(e.data.res))
        var code = e.data.code;
        if (code == 0) {
          var objs = e.data.res;
          
          if (objs.length < that.data.pageSize) {
            // 加载完了
            that.setData({ hideBottomLabel: false });
          }
          else
          {
            that.setData({ hideBottomLabel: true });
          }
          for (var i = 0; i < objs.length; i++) {
            var obj = objs[i];
            var img = obj['img'];
            // console.log('img:'+img);
            var imgs = img.split(",");
            // console.log(imgs);
            obj.imgs = imgs;
            obj.hideTop = (obj.top=='0')
          }

          // ye==1 表示下拉刷新或第一次进入页面
          if (ye == 1) {
            that.setData({ list: objs });
          } else {
            that.setData({
              list: that.data.list.concat(objs)
            });
          }
        } else {
          var msg = e.data.msg;
          console.log(msg);
          if (msg) {
            wx.showToast({
              title: msg,
            })
          }
          else {
            wx.showToast({
              title: JSON.stringify(e.data),
            })
          }
        }
      },
      fail: function (failed) {
        wx.showToast({
          title: '访问失败',
        })
        that.hideLoading()
        // wx.hideLoading();
        // that.stopRefreshView();
        console.log(failed);
      }
    })
  },

  onPageScroll: function (e) {
    var hidetop = this.data.hidetop;
    var tab = this.data.tab;
    var that = this;

    // that.setData({
    //   scrollTop: e.scrollTop
    // })   

    if (JSON.stringify(tab) !== JSON.stringify([true, true, true]) && hidetop==false)
    {
      return;
    }

    that.setData({
      hidetop: e.scrollTop < 250,
      // overHeight: e.scrollTop >= 250
    })
    // console.log('scrollTop' + that.data.scrollTop);
    // console.log('hidetop:' + that.data.hidetop);

    // setTimeout(function () {
    //   console.log("----Countdown----");
    //   if(that.data.hidetop)
    //   {
    //     that.setData({
    //       hidetop:true
    //     })
    //   }
    // }, 1000);
    
  },
  onPullDownRefresh:function(){
    var that = this;
    that.setData({
      ye:1
    });
    that.getDataList()
  }
})


// 倒计时
function Countdown() {
  timer = setTimeout(function () {
    console.log("----Countdown----");
    Countdown();
  }, 1000);
};
